//
//  LandmarkList.swift
//  Landmarks
//
//  Created by yafei li on 2024/6/17.
//

import SwiftUI

struct LandmarkList: View {
    
    @Environment(ModelData.self) var modelData
    
    @State private var showFavoritesOnly = false
    
    @State private var filter = FilterCategory.all
    
    @State private var selectedLandmark: Landmark?
    
    enum FilterCategory: String, CaseIterable, Identifiable {
            case all = "All"
            case lakes = "Lakes"
            case rivers = "Rivers"
            case mountains = "Mountains"


            var id: FilterCategory { self }
    }
    
    
    var filterLandmarks: [Landmark] {
        modelData.landmarks.filter { landmark in
            (!showFavoritesOnly || landmark.isFavorite)  && (filter == .all || filter.rawValue == landmark.category.rawValue)
        }
    }
    
    var title: String {
      let title = filter == .all ? "Landmarks" : filter.rawValue
      return showFavoritesOnly ? "Favorite \(title)" : title
    }
    
    var index: Int? {
       modelData.landmarks.firstIndex(where: { $0.id == selectedLandmark?.id })
    }

    
    var body: some View {
        @Bindable var modelData = modelData
        
        NavigationSplitView {
            List {
                Toggle(isOn: $showFavoritesOnly, label: {
                    Text("Favorites only")
                })
                
                ForEach(filterLandmarks) { landmark in
                    NavigationLink {
                        LandmarkDetail(landmark: landmark)
                    } label: {
                        LandmarkRow(landmark: landmark)
                    }
                    .tag(landmark)
                }
            }
            .animation(.default, value: filterLandmarks)
            .navigationTitle(title)
            .frame(minWidth: 300)
            .toolbar(content: {
                ToolbarItem {
                    Menu {
                        
                      Picker("Category", selection: $filter) {
                          ForEach(FilterCategory.allCases) { category in
                              Text(category.rawValue).tag(category)
                          }
                      }
                      .pickerStyle(.menu)
                        
                        Toggle(isOn: $showFavoritesOnly) {
                                                  Label("Favorites only", systemImage: "star.fill")
                                              }
                    } label: {
                        Label("Filter", systemImage: "slider.horizontal.3")
                    }
                }
            })
        } detail: {
            Text("Select a Landmark")
        }
        .focusedValue(\.selectedLandmark, $modelData.landmarks[index ?? 0])
    }
}

#Preview {
    let modelData = ModelData()
    
    return LandmarkList()
        .environment(modelData)
}
